<?php
/*
PluginName:博客日历
PluginUrl:http://www.lisijie.org
PluginAuthor:lisijie
PluginAuthorUrl:http://www.lisijie.org
PluginDesc:博客日历widget for Jblog2
PluginVer:2.0.0
*/

class CalendarWidget extends Widget {

	function CalendarWidget() {
		$this->Widget(array('title'=>'博客日历'));
	}

	function display() {
		global $get;
		if ( $get['mod'] == 'archives' && $get['date'] ) {
			list($year, $month, $day) = explode('-', $get['date']);
			$day = max(1, (int)$day);
		} else {
			list($year, $month, $day) = explode('-',get_date(NOW, 'Y-m-d'));
		}
		$week_start = get_date(mktime(0,0,0,$month,1,$year),'w'); //星期中的第几天
		$month_days = get_date(mktime(0,0,0,$month,1,$year),'t'); //本月份天数
		$prev_month = strtotime('-1 month', mktime(0,0,0,$month,$day,$year) + config('timezone') * 3600);
		$prev_month = get_date($prev_month,'Y-m');
		$next_month = strtotime('+1 month', mktime(0,0,0,$month,$day,$year) + config('timezone') * 3600);
		$next_month = get_date($next_month,'Y-m');
		$data = array();
		$result = $this->db->query("SELECT `day`,COUNT(*) AS num FROM ".tname('calendar')." WHERE yearmonth = '{$year}{$month}' GROUP BY `day`");
		while ($row = $this->db->fetch_array($result)) {
			$data[$row['day']] = $row['num'];
		}
		$output .= '<div class="calendar"><table cellpadding="2" class="month'.(int)$month.'">'."\n";
		$output .= '<caption><a href="'.url("mod=archives&date={$prev_month}").'">&laquo;</a> '.$year.'年'.$month.'月 <a href="'.url("mod=archives&date=$next_month").'">&raquo;</a></caption>'."\n";
		$output .= '<tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>'."\n";
		$output .= '<tr>'."\n";
		$n = 0;
		for ($i=0; $i<$week_start; $i++) {
			$output .= "<td></td>\n";
			$n ++;
		}
		for ($i=1; $i<=$month_days; $i++) {
			$href_s = $href_e = '';
			if ($data[$i] > 0) {
				$href_s = '<a href="'.url("mod=archives&date=".sprintf('%04d-%02d-%02d',$year,$month,$i)).'" title="'.$i.'日共有'.$data[$i].'篇文章">';
				$href_e = '</a>';
			}
			if ($n && $n%7 == 0) $output .= "</tr><tr>\n";
			if ($year.$month.$i == get_date(NOW,'Ymj')) {
				$output .= '<td class="today">'.$href_s.$i.$href_e.'</td>';
			} else {
				$output .= '<td>'.$href_s.$i.$href_e.'</td>';
			}
			$n ++;
		}
		$output .= "</tr>\n</table>\n</div>\n";
		return $output;
	}
}
?>